package my.mall.front.api.config

import my.mall.common.annotation.Login
import my.mall.common.enums.RespMetaEnum
import my.mall.common.exception.WebBaseException
import my.mall.common.util.JwtUtils.verifyToken
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.MethodParameter
import org.springframework.http.HttpHeaders
import org.springframework.lang.Nullable
import org.springframework.stereotype.Component
import org.springframework.util.StringUtils
import org.springframework.web.bind.support.WebDataBinderFactory
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.method.support.ModelAndViewContainer

@Component
class LoginResolver : HandlerMethodArgumentResolver {

    @Value("\${spring.profiles.active}")
    private lateinit var profiles: String

    override fun supportsParameter(parameter: MethodParameter): Boolean {
        return parameter.parameterType.isAssignableFrom(Long::class.java) && parameter.hasParameterAnnotation(
            Login::class.java
        )
    }

    override fun resolveArgument(
        parameter: MethodParameter,
        @Nullable container: ModelAndViewContainer?,
        request: NativeWebRequest,
        @Nullable factory: WebDataBinderFactory?
    ): Any {
        var token = request.getHeader(HttpHeaders.AUTHORIZATION)
        if (!StringUtils.hasLength(token)) {
            throw WebBaseException(RespMetaEnum.NOT_LOGIN)
        }
        token = token!!.trim { it <= ' ' }
        return verifyToken(token)
    }
}
